package com.eddie.auction.utils;

import com.eddie.auction.config.ConfigManager;

import java.sql.*;

/**
 * @author Eddie
 * @date 2022/08/01 13:37
 **/
public class DataBaseUtil {

    private DataBaseUtil() {

    }

    //饿汉式创建单例
    private static final DataBaseUtil instance = new DataBaseUtil();

    public static DataBaseUtil getInstance() {
        return instance;
    }

    private static final String driver = ConfigManager.getProperty("driver");

    private static final String url = ConfigManager.getProperty("url");

    private static final String username = ConfigManager.getProperty("username");

    private static final String password = ConfigManager.getProperty("password");

    private static final ThreadLocal<Connection> threadLocal = new ThreadLocal<>();

    static {
        try {
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取链接
     * @return 数据库连接
     * @throws SQLException sql异常
     */
    public Connection getConnection() throws SQLException {
        Connection connection = threadLocal.get();
        if (connection == null || connection.isClosed()) {
            connection = DriverManager.getConnection(url, username, password);
            if (connection.getAutoCommit())
                connection.setAutoCommit(false);
            threadLocal.set(connection);
        }
        return connection;
    }

    /**
     * 关闭连接
     */
    public void closeConnection() {
        Connection connection = threadLocal.get();
        threadLocal.remove();
        try {
            if(connection!=null && !connection.isClosed()) connection.close();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public void closeStatement(Statement stmt,ResultSet rs) {
        try {
            if(rs!=null&&!rs.isClosed()) rs.close();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        try {
            if(stmt!=null&&!stmt.isClosed())
                stmt.close();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }



}
